package com.example.musicaiap.mvi.base

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.flowWithLifecycle
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow

/**
 * 收集UiState并作为State返回，绑定到生命周期
 */
@Composable
fun <T : UiState> StateFlow<T>.collectAsStateWithLifecycle(
    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
    minActiveState: Lifecycle.State = Lifecycle.State.STARTED
): androidx.compose.runtime.State<T> {
    val initialValue = this.value
    val flow = this.flowWithLifecycle(
        lifecycleOwner.lifecycle,
        minActiveState
    )
    return flow.collectAsState(initialValue)
}

/**
 * 收集MviViewModel的状态和效应
 */
@Composable
fun <S : UiState, I : UiIntent, E : UiEffect> MviViewModel<S, I, E>.CollectState(
    effectHandler: (suspend (E) -> Unit)? = null
): androidx.compose.runtime.State<S> {
    val state = uiState.collectAsStateWithLifecycle()
    
    if (effectHandler != null) {
        LaunchedEffect(true) {
            uiEffect.collect { effect ->
                effectHandler(effect)
            }
        }
    }
    
    return state
}

/**
 * 仅收集MviViewModel的效应
 */
@Composable
fun <E : UiEffect> Flow<E>.CollectEffect(
    effectHandler: suspend (E) -> Unit
) {
    LaunchedEffect(true) {
        this@CollectEffect.collect { effect ->
            effectHandler(effect)
        }
    }
}